/**
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * Copyright 2007
 * @author Florian Hackenberger <florian@hackenberger.at>
 * @portions 2012 Remo Wasmer
 */

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.pdfbox.exceptions.COSVisitorException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.edit.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDType1Font;

import net.htmlparser.jericho.Element;
import net.htmlparser.jericho.Source;
import net.htmlparser.jericho.StartTag;

public class unWrite {


	/**
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			if(args.length < 1 || args[0] == "--help" || args[0] == "-h") {
				System.out.print(
						"Usage: java com.acoveo.hocrtopdf.HocrToPdf INPUTURL.html OUTPUTURL.pdf\n" +
						"\n" +
						"Converts hOCR files into PDF\n" +
						"\n" +
						"Example: java com.acoveo.hocrtopdf.HocrToPdf file:///home/username/hocr.html ./output.pdf\n");
				if(args.length < 1)
					System.exit(-1);
				else
					System.exit(0);
			}
			URL inputHOCRFile = null;
			try {
				inputHOCRFile = new URL(args[0]);
			} catch (MalformedURLException e) {
				System.out.println("The first parameter has to be a valid URL");
				System.exit(-1);
			}
			
			// The resolution of a PDF file (using iText) is 72pt per inch
			float pointsPerInch = 72.0f;
			
			// Using the jericho library to parse the HTML file
			Source source=new Source(inputHOCRFile);

			// Find the tag of class ocr_page in order to load the scanned image
			StartTag pageTag = source.getNextStartTag(0, "class", "ocr_page", false);
			Pattern imagePattern = Pattern.compile("image\\s+([^;]+)");
			Matcher imageMatcher = imagePattern.matcher(pageTag.getElement().getAttributeValue("title"));
			if(!imageMatcher.find()) {
				System.out.println("Could not find a tag of class \"ocr_page\", aborting.");
				System.exit(-1);
			}
			// In order to place text behind the recognised text snippets we are interested in the bbox property		
			Pattern bboxPattern = Pattern.compile("bbox(\\s+\\d+){4}");
			// This pattern separates the coordinates of the bbox property
			Pattern bboxCoordinatePattern = Pattern.compile("(\\d+)\\s+(\\d+)\\s+(\\d+)\\s+(\\d+)");
			// Only tags of the ocr_line class are interesting
			StartTag ocrLineTag = source.getNextStartTag(0, "class", "ocr_line", false);
			
			
			
	        // the document
	        PDDocument doc = null;
	        try
	        {
	            doc = new PDDocument();

	            PDPage page = new PDPage();
	            doc.addPage( page );
	            PDFont font = PDType1Font.HELVETICA_BOLD;

	            PDPageContentStream contentStream = new PDPageContentStream(doc, page, true, true);
	                         
         
	        
	        
			while(ocrLineTag != null) {
				Element lineElement = ocrLineTag.getElement();
				Matcher bboxMatcher = bboxPattern.matcher(lineElement.getAttributeValue("title"));
				if(bboxMatcher.find()) {
					// We found a tag of the ocr_line class containing a bbox property
					Matcher bboxCoordinateMatcher = bboxCoordinatePattern.matcher(bboxMatcher.group());
					bboxCoordinateMatcher.find();
					int[] coordinates = {Integer.parseInt((bboxCoordinateMatcher.group(1))),
							Integer.parseInt((bboxCoordinateMatcher.group(2))),
							Integer.parseInt((bboxCoordinateMatcher.group(3))),
							Integer.parseInt((bboxCoordinateMatcher.group(4)))};
					String line = lineElement.getContent().getTextExtractor().toString();
					
					// Put the text into the PDF
					System.out.println(coordinates[0]);
					System.out.println(coordinates[3]);
					System.out.println(line);
					
		            contentStream.beginText();
		            contentStream.setFont(font, 8);
		            contentStream.moveTextPositionByAmount(coordinates[0], 792-coordinates[3]);
		            contentStream.drawString(line);
		            contentStream.endText();
					
				}
				ocrLineTag = source.getNextStartTag(ocrLineTag.getEnd(), "class", "ocr_line", false);		
			}
			
			contentStream.close();
            doc.save( "outtest.pdf" );
        } catch (COSVisitorException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	        
        finally
        {
            if( doc != null )
            {
                doc.close();
            }
        }
	        
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}